package com.itheima.train.manager.mq;

import com.alibaba.fastjson.JSON;
import com.itheima.train.manager.domain.Order;
import com.itheima.train.manager.domain.OrderSynEs;
import com.itheima.train.manager.domain.TbRidingPlanDate;
import com.itheima.train.manager.service.EsIndexService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class EsConsumer {

    // 创建一个日志对象
    private Logger logger = LoggerFactory.getLogger(EsConsumer.class) ;

    @Autowired
    private EsIndexService esIndexService ;

    @RabbitListener(queues = "syn_riding_plan_to_es_queue")
    public void synRidingPlan(String ridingPlan , Message message , Channel channel) {

        try {

            // 将数据解析成指定的对象
            TbRidingPlanDate tbRidingPlanDate = JSON.parseObject(ridingPlan , TbRidingPlanDate.class) ;
            esIndexService.addDocument(tbRidingPlanDate);
            logger.info("【同步乘车计划获取成功了】---->" + ridingPlan);

            // 手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);

        } catch (IOException e) {
            e.printStackTrace();
            logger.error("【同步乘车计划获取失败了】---->" + ridingPlan);
        }

    }

    @RabbitListener(queues = "syn_stock_es_queue")
    public void synStock(String orderSynEsJson , Message message , Channel channel) {

        try {

            // 解析json数据
            OrderSynEs orderSynEs = JSON.parseObject(orderSynEsJson, OrderSynEs.class);

            // 调用esIndexService中的方法实现库存的同步操作
            esIndexService.synStockInfo(orderSynEs) ;

            // 手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RabbitListener(queues = "back_stock_es_queue")
    public void backStock(String orderJson , Message message , Channel channel) {

        try {

            // 解析json数据
            Order order = JSON.parseObject(orderJson, Order.class);

            // 调用esIndexService中的方法实现库存的同步操作
            esIndexService.backStock(order) ;

            logger.info("【es库存回退成功了】---->" + orderJson);

            // 手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
